const WechatPay = require('wechatpay-node-v3');
const AlipaySdk = require('alipay-sdk');
const config = require('../config');
const logger = require('../utils/logger');

// 微信支付配置
const wechatPayConfig = {
  appid: config.wechat.appId,
  mchid: config.payment.wechatPay.mchId,
  publicKey: config.payment.wechatPay.certPath,
  privateKey: config.payment.wechatPay.keyPath,
  notify_url: config.payment.wechatPay.notifyUrl,
};

// 支付宝配置
const alipayConfig = {
  appId: config.payment.alipay.appId,
  privateKey: config.payment.alipay.privateKey,
  alipayPublicKey: config.payment.alipay.publicKey,
  gateway: config.payment.alipay.sandbox ? 'https://openapi.alipaydev.com/gateway.do' : 'https://openapi.alipay.com/gateway.do',
  notify_url: config.payment.alipay.notifyUrl,
};

class WechatPayService {
  constructor() {
    this.pay = new WechatPay(wechatPayConfig);
  }

  /**
   * 创建微信支付订单
   * @param {string} outTradeNo - 商户订单号
   * @param {number} totalFee - 总金额
   * @param {string} body - 商品描述
   * @param {string} openid - 用户标识
   * @returns {Promise<Object>} - 订单结果
   */
  async createOrder({ outTradeNo, totalFee, body, openid }) {
    try {
      const result = await this.pay.transactions_jsapi({
        description: body,
        out_trade_no: outTradeNo,
        amount: {
          total: totalFee,
          currency: 'CNY'
        },
        payer: {
          openid: openid
        }
      });

      return result;
    } catch (error) {
      logger.error('WechatPay createOrder error:', error);
      throw error;
    }
  }

  /**
   * 验证微信支付通知
   * @param {Object} headers - 请求头
   * @param {string} body - 请求体
   * @returns {Promise<boolean>} - 验证结果
   */
  async verifyNotify(headers, body) {
    try {
      return await this.pay.verifyNotify(headers, body);
    } catch (error) {
      logger.error('WechatPay verifyNotify error:', error);
      throw error;
    }
  }

  /**
   * 查询微信支付订单
   * @param {string} outTradeNo - 商户订单号
   * @returns {Promise<Object>} - 订单结果
   */
  async queryOrder(outTradeNo) {
    try {
      return await this.pay.query({
        out_trade_no: outTradeNo
      });
    } catch (error) {
      logger.error('WechatPay queryOrder error:', error);
      throw error;
    }
  }

  /**
   * 微信退款
   * @param {string} outTradeNo - 商户订单号
   * @param {string} outRefundNo - 退款订单号
   * @param {number} totalFee - 总金额
   * @param {number} refundFee - 退款金额
   * @returns {Promise<Object>} - 退款结果
   */
  async refund({ outTradeNo, outRefundNo, totalFee, refundFee }) {
    try {
      return await this.pay.refunds({
        out_trade_no: outTradeNo,
        out_refund_no: outRefundNo,
        amount: {
          refund: refundFee,
          total: totalFee,
          currency: 'CNY'
        }
      });
    } catch (error) {
      logger.error('WechatPay refund error:', error);
      throw error;
    }
  }
}

class AlipayService {
  constructor() {
    this.alipay = new AlipaySdk(alipayConfig);
  }

  /**
   * 创建支付宝支付订单
   * @param {string} outTradeNo - 商户订单号
   * @param {number} totalAmount - 总金额
   * @param {string} subject - 商品描述
   * @returns {Promise<Object>} - 订单结果
   */
  async createOrder({ outTradeNo, totalAmount, subject }) {
    try {
      const bizContent = {
        out_trade_no: outTradeNo,
        total_amount: totalAmount,
        subject: subject,
        product_code: 'FAST_INSTANT_TRADE_PAY'
      };

      const result = await this.alipay.exec(
        'alipay.trade.create',
        {
          bizContent: bizContent,
          notify_url: alipayConfig.notify_url
        }
      );

      return result;
    } catch (error) {
      logger.error('Alipay createOrder error:', error);
      throw error;
    }
  }

  /**
   * 验证支付宝支付通知
   * @param {Object} params - 通知参数
   * @returns {Promise<boolean>} - 验证结果
   */
  async verifyNotify(params) {
    try {
      return await this.alipay.checkNotifySign(params);
    } catch (error) {
      logger.error('Alipay verifyNotify error:', error);
      throw error;
    }
  }

  /**
   * 查询支付宝支付订单
   * @param {string} outTradeNo - 商户订单号
   * @returns {Promise<Object>} - 订单结果
   */
  async queryOrder(outTradeNo) {
    try {
      const result = await this.alipay.exec('alipay.trade.query', {
        bizContent: {
          out_trade_no: outTradeNo
        }
      });

      return result;
    } catch (error) {
      logger.error('Alipay queryOrder error:', error);
      throw error;
    }
  }

  /**
   * 支付宝退款
   * @param {string} outTradeNo - 商户订单号
   * @param {number} refundAmount - 退款金额
   * @param {string} outRefundNo - 退款订单号
   * @returns {Promise<Object>} - 退款结果
   */
  async refund({ outTradeNo, refundAmount, outRefundNo }) {
    try {
      const result = await this.alipay.exec('alipay.trade.refund', {
        bizContent: {
          out_trade_no: outTradeNo,
          refund_amount: refundAmount,
          out_request_no: outRefundNo
        }
      });

      return result;
    } catch (error) {
      logger.error('Alipay refund error:', error);
      throw error;
    }
  }
}

module.exports = {
  wechatPay: new WechatPayService(),
  alipay: new AlipayService()
}; 